import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/9 20:24
 * @description 数学
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.getPermutation(4, 9);
    }
    public String getPermutation(int n, int k) {
        int[] factorial = new int[n];
        factorial[0] = 1;
        // 为什么求到f[n-1]的阶乘即可，因为选取一个元素ai, 以其为首最多有(n-1)!种排列
        for (int i = 1; i < n; ++i) {
            factorial[i] = factorial[i - 1] * i;
        }
        // 首先将k-1，
        --k;
        StringBuffer ans = new StringBuffer();
        // 记录每个元素是否被使用
        int[] valid = new int[n + 1];
        Arrays.fill(valid, 1);
        for (int i = 1; i <= n; ++i) {
            // 第k个排列的首元素ai
            int order = k / factorial[n - i] + 1;
            for (int j = 1; j <= n; ++j) {
                order -= valid[j];
                if (order == 0) {
                    ans.append(j);
                    valid[j] = 0;
                    break;
                }
            }
            k %= factorial[n - i];
        }
        return ans.toString();
    }
}
